package com.cyy.common.config.jackson;

import com.cyy.common.constant.DateEnum;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.regex.Pattern;

public interface BaseTimeDeserializer {

    Pattern DATE_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$");
    Pattern DATETIME_PATTERN = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$");

    /**
     * 将页面传入的原日期字符串进行转换
     */
    default LocalDateTime getLocalDateTimeBySource(String source) {
        if (source == null || source.trim().isEmpty()) {
            return null;
        }
        source = source.trim();

        if (!DATE_PATTERN.matcher(source).matches() && !DATETIME_PATTERN.matcher(source).matches()) {
            throw new RuntimeException("日期参数格式错误: " + source);
        }

        if (DATE_PATTERN.matcher(source).matches()) {
            LocalDate localDate = LocalDate.parse(source, DateEnum.COMMON_MONTH_DAY.getDateTimeFormatter());
            return localDate.atStartOfDay();
        }
        return LocalDateTime.parse(source + " 00:00:00", DateEnum.COMMON_DATE_TIME.getDateTimeFormatter());
    }

}
